using System;
using System.Collections.Generic;

namespace lucere.io.concurrency
{
	/// <summary>
	/// Implements <see cref="LockFactory"></see> for a single in-process instance,
	/// meaning all locking will take place through this one instance.
	/// Only use this <see cref="LockFactory"></see> when you are certain all
	/// IndexReaders and IndexWriters for a given index are running
	/// against a single shared in-process Directory instance.  This is
	/// currently the default locking for RAMDirectory.
	/// LockFactory
	/// </summary>
	public class SingleInstanceLockFactory : LockFactory
	{
		private readonly HashSet<String> _locks = new HashSet<String>();
		///<summary>
		///Return a new Lock instance identified by lockName.
		///<param name="lockName">name of the lock to be created.</param>
		///</summary>
		public override ILock MakeLock(string lockName)
		{
			// We do not use the LockPrefix at all, because the private
			// HashSet instance effectively scopes the locking to this
			// single Directory instance.
			return new SingleInstanceLock(_locks, lockName);
		}

		///<summary>
		/// Attempt to clear (forcefully unlock and remove) the
		/// specified lock.  Only call this at a time when you are
		/// certain this lock is no longer in use.
		/// <param name="lockName">name of the lock to be cleared.</param>
		/// </summary>
		public override void ClearLock(string lockName)
		{
			lock (_locks)
			{
				if (_locks.Contains(lockName))
					_locks.Remove(lockName);
			}
		}
	}
}